package kotan.view.table.editor;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import kotan.Kotan;
import kotan.datastore.api.Text;
import kotan.model.EntityModel;

public class TextEditorPanel  extends JPanel {
    private static final long serialVersionUID = 1L;
    JButton applyButton;
    private JTextArea textArea;
    private Text text;
    private EntityModel model;
    private int column;

    TextEditorPanel() {
        initComponents();
        this.setBorder(BorderFactory.createEmptyBorder(2, 5, 3, 5));
        this.setPreferredSize(new Dimension(300, 200));
    }

    private void initComponents() {
        textArea = new JTextArea();
        textArea.setRows(5);
        JScrollPane scrollPane = new JScrollPane(textArea);
        // Apply / Cancel
        applyButton = new JButton();
        applyButton.setText("Apply");
        applyButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                onApply();
            }
        });
        JButton cancelButton = new JButton();
        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });
        // Layout
        this.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 1;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.anchor = GridBagConstraints.EAST;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(3, 5, 2, 5);
        add(scrollPane, gbc);
        // 
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 1;
        gbc.weightx = 1.0;
        gbc.weighty = 0.0;
        gbc.anchor = GridBagConstraints.NORTHEAST;
        gbc.fill = GridBagConstraints.NONE;
        gbc.insets = new Insets(3, 5, 2, 5);
        {
            JPanel panel = new JPanel(new FlowLayout());
            panel.add(cancelButton);
            panel.add(applyButton);
            add(panel, gbc);
        }
    }
    
    protected void onApply() {
        String newText = textArea.getText();
        if (newText.equals(text)) return;
        Kotan.get().getDatastore().update(model, column, new Text(newText));
    }

    protected void onCancel() {
    }
    
    void init(EntityModel model, int column, Text text) {
        this.model = model;
        this.column = column;
        this.text = text;
        this.textArea.setText(text.getValue());
    }


}
